package com.example.victory.utils;

import com.example.victory.utils.SortingUtils;
import com.example.victory.exception.GlobalError;
import com.example.victory.exception.GlobalException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class ExportExcelUtil<T> {

    //获取父类的所有字段
    private static Field[] getSuperClassFields(Field[] tableFields, Class<?> clazz) {
        Class<?> superClazz = clazz.getSuperclass();
        if (superClazz.equals(Object.class)) {
            return tableFields;
        }
        Field[] tableSuperFields = superClazz.getDeclaredFields();

        Field[] c = new Field[tableFields.length + tableSuperFields.length];
        System.arraycopy(tableFields, 0, c, 0, tableFields.length);
        System.arraycopy(tableSuperFields, 0, c, tableFields.length, tableSuperFields.length);
        getSuperClassFields(c, superClazz);
        return c;
    }

    /**
     * 这是一个通用的方法，利用了JAVA的反射机制，可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL
     * 的形式输出到指定IO设备上
     *
     * @param title      表格标题名
     * @param dataSet    需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。
     * @param targetPath 需要导出目标文件地址路径
     * @param pattern    如果有时间数据，设定输出格式。默认为"yyy-MM-dd"
     */
    public void exportExcel(String title, List<T> dataSet, String targetPath, String pattern) {
        exportExcel(title, dataSet, targetPath, pattern, null);
    }

    /**
     * 这是一个通用的方法，利用了JAVA的反射机制，可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL
     * 的形式输出到指定IO设备上
     *
     * @param title             表格标题名
     * @param dataSet           需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。
     * @param targetPath        需要导出目标文件地址路径
     * @param pattern           如果有时间数据，设定输出格式。默认为"yyy-MM-dd"
     * @param sheetSeparateName 分组字段
     */
    public void exportExcel(String title, List<T> dataSet, String targetPath, String pattern, String sheetSeparateName) {

        if (dataSet == null || dataSet.size() == 0) {
            throw new GlobalException(GlobalError.GLOBAL_EXPORT_NOT_ALLOWED_OF_NO_DATA);
        }

        if (dataSet != null && dataSet.size() > 65536) {
            throw new GlobalException(GlobalError.GLOBAL_EXPORT_DATA_TOO_MUCH);
        }

        try {
            File targetFile = new File(targetPath);
            FileUtils.forceMkdirParent(targetFile);

            // 声明一个工作薄
            HSSFWorkbook workbook = new HSSFWorkbook();

            if (StringUtils.isNotEmpty(sheetSeparateName)) {
                Map<Object, List<T>> map = separate(dataSet, sheetSeparateName);
                // 循环生成多个表格
                for (Map.Entry<Object, List<T>> entry : map.entrySet()) {
                    List<T> list = entry.getValue();
                    if(title != null && title.startsWith("$") && list != null && list.size() > 0){
                        Object value = getFieldValue(list.get(0), title.replace("$",""));
                        createSheet(workbook, value.toString(), entry.getValue(), pattern);
                    } else {
                        createSheet(workbook, entry.getKey().toString(), entry.getValue(), pattern);
                    }
                }
            } else {
                // 生成一个表格
                createSheet(workbook, title, dataSet, pattern);
            }

            File f = new File(targetPath);
            FileOutputStream fs = null;
            try {
                fs = new FileOutputStream(f);
                workbook.write(fs);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } catch (Exception e) {
            log.error("导出失败", e);
            throw new GlobalException(GlobalError.GLOBAL_EXPORT_ERROR);
        }

    }

    private Object getFieldValue(T t, String headName) throws Exception {

        Field[] heads = getSuperClassFields(t.getClass().getDeclaredFields(), t.getClass());
        Field field = null;

        //获取字段注解的表头
        for (int i = 0; i < heads.length; i++) {
            //过滤掉没加注解的字段
            if (heads[i].getAnnotations().length == 0)
                continue;
            ExcelAnno exAnno = (ExcelAnno) heads[i].getAnnotations()[0];
            String headStr = exAnno.head();
            if (headStr.equals(headName)) {
                field = heads[i];
            }
        }

        Object value = null;
        if(field != null){
            String fieldName = field.getName();
            String getMethodName = "get"
                    + fieldName.substring(0, 1).toUpperCase()
                    + fieldName.substring(1);
            Class tCls = t.getClass();
            Method getMethod = tCls.getMethod(getMethodName,
                    new Class[]
                            {});
            value = getMethod.invoke(t, new Object[]
                    {});
        }

        return value;
    }

    private Map<Object, List<T>> separate(List<T> dataSet, String sheetSeparateName) throws Exception {
        T tempT = dataSet.get(0);
        Field[] heads = getSuperClassFields(tempT.getClass().getDeclaredFields(), tempT.getClass());
        Field field = null;
        //获取字段注解的表头
        for (int i = 0; i < heads.length; i++) {
            //过滤掉没加注解的字段
            if (heads[i].getAnnotations().length == 0) continue;
            ExcelAnno exAnno = (ExcelAnno) heads[i].getAnnotations()[0];
            String headStr = exAnno.head();
            if (headStr.equals(sheetSeparateName)) {
                field = heads[i];
            }
        }

        Map<Object, List<T>> classMap = new LinkedHashMap<>();
        if (field != null) {
            for (T t : dataSet) {
                String fieldName = field.getName();
                String getMethodName = "get"
                        + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                Class tCls = t.getClass();
                Method getMethod = tCls.getMethod(getMethodName,
                        new Class[]
                                {});
                Object value = getMethod.invoke(t, new Object[]
                        {});
                if (!classMap.containsKey(value)) {
                    classMap.put(value, new ArrayList<>());
                }
                classMap.get(value).add(t);
            }
        }
        return classMap;
    }

    public void createSheet(HSSFWorkbook workbook, String title, List<T> dataSet, String pattern)
            throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为20个字节
        sheet.setDefaultColumnWidth((short) 20);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);

        // 生成并设置另一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);

        if (dataSet == null || dataSet.size() == 0) return;
        T tempT = dataSet.get(0);
        Field[] heads = getSuperClassFields(tempT.getClass().getDeclaredFields(), tempT.getClass());
        List<Head> headList = new ArrayList<>();
        //获取字段注解的表头
        for (int i = 0; i < heads.length; i++) {
            //过滤掉没加注解的字段
            if (heads[i].getAnnotations().length == 0) continue;
            ExcelAnno exAnno = (ExcelAnno) heads[i].getAnnotations()[0];
            Head head = new Head(exAnno.head(), exAnno.order(), heads[i]);
            if(head != null && head.getOrder() >= 0){
                // 排序等于或者大于0的列才会导出
                headList.add(head);
            }
        }
        SortingUtils.sortAscNullLast(headList, o -> o.getOrder());
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headList.size(); i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headList.get(i).getHead());
            cell.setCellValue(text);

        }
        // 遍历集合数据，产生数据行
        Iterator<T> it = dataSet.iterator();
        int index = 0;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            T t = (T) it.next();
            for (Head head : headList) {
                HSSFCell cell = row.createCell(headList.indexOf(head));
                cell.setCellStyle(style2);
                String fieldName = head.getField().getName();
                String getMethodName = "get"
                        + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                Class tCls = t.getClass();
                Method getMethod = tCls.getMethod(getMethodName,
                        new Class[]
                                {});
                Object value = getMethod.invoke(t, new Object[]
                        {});
                // 判断值的类型后进行强制类型转换
                String textValue = null;
                if (value == null) {
                    cell.setCellValue("");
                }
                if (value instanceof Integer) {
                    int intValue = (Integer) value;
                    cell.setCellValue(intValue);
                } else if (value instanceof Float) {
                    float fValue = (Float) value;
                    cell.setCellValue(fValue);
                } else if (value instanceof Double) {
                    double dValue = (Double) value;
                    cell.setCellValue(dValue);
                } else if (value instanceof Long) {
                    long longValue = (Long) value;
                    cell.setCellValue(longValue);
                } else if (value instanceof Date) {
                    Date date = (Date) value;
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                    textValue = sdf.format(date);
                    cell.setCellValue(textValue);
                } else {
                    // 其它数据类型都当作字符串简单处理
                    textValue = value == null ? "" : value.toString();
                    cell.setCellValue(textValue);
                }
            }
        }
    }

    @Data
    class Head {
        String head;
        int order;
        Field field;

        Head(String head, int order, Field field) {
            this.head = head;
            this.order = order;
            this.field = field;
        }
    }
}
